package woa.sort.test20230210;

import java.util.Arrays;

/**
 * 递推公式：quick_sort(p…r) = quick_sort(p…q-1) + quick_sort(q+1… r)
 * 终止条件：p >= r
 *
 * @author wangpeng
 * @date 2023/2/16 21:50
 */
public class QuickSort1 {

    public static void sort(int[] arr, int p, int r) {
        if (p >= r) {
            return;
        }
        int q = partition(arr, p, r);
        sort(arr, p, q - 1);
        sort(arr, q + 1, r);
    }

    public static int partition(int[] arr, int p, int r) {
        int pivot = arr[r];
        int i = p;
        for(int j = p; j < r; ++j) {
            if (arr[j] < pivot) {
                int tmp = arr[i];
                arr[i++] = arr[j];
                arr[j] = tmp;
            }
        }

        int tmp = arr[i];
        arr[i] = arr[r];
        arr[r] = tmp;

        return i;
    }

    public static void main(String[] args) {
        int[] arr = {3,4,1,3,5,6,78,1,3,3,3,2};
//        int[] arr = {3,2,8,7,2};
        sort(arr,0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }
}
